package online.misscl.lsy.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头里面获取token
        String token = request.getHeader("Authorization");
        System.out.println(request.getRequestURI());
        response.setContentType("application/json;charset=utf8");
        Map<String, Object> map = new HashMap<>();

        if(token == null) {
            map.put("code", 401);
            map.put("msg", "没有token");
            response.getWriter().write(JSON.toJSONString(map));
            response.getWriter().write(JSON.toJSONString(map));
            return false;
        }

        //验证token
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256("zxcvbnmasdfghjklqwertyuiop123456" )).build().verify(token);
//            System.out.println(verify);
//            String userId = verify.getClaim("userId").asString();
//            String auth = verify.getClaim("auth").asString();
//
//            System.out.println(userId);
//            System.out.println(auth);
        }catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg", "token过期");
            response.getWriter().write(JSON.toJSONString(map));
            return false;
//            throw  new TokenExpiredException("令牌过期");
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg", "token令牌不正确");
            response.getWriter().write(JSON.toJSONString(map));
            return false;
//            throw  new RuntimeException("令牌不正确");
        }catch (NullPointerException e){
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg", "缺少token");
            response.getWriter().write(JSON.toJSONString(map));
            return false;
//            throw new NullPointerException("缺少token");
        }

        return true;
    }
}
